package com.newcapec.common.utils.iot;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newcapec.common.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
/*import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;*/

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.*;

/**
 * 签名工具
 * @author steven
 */
public class SignUtils {

    /**
     * 将byte[]转为各种进制的字符串
     *
     * @param bytes byte[]
     * @param radix 可以转换进制的范围，从Character.MIN_RADIX到Character.MAX_RADIX，超出范围后变为10进制
     * @return 转换后的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
    }

    /**
     * base 64 encode
     *
     * @param bytes 待编码的byte[]
     * @return 编码后的base 64 code
     */
    public static String base64Encode(byte[] bytes) {
        java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();
        return base64Encoder.encodeToString(bytes);
    }

    /**
     * base 64 decode
     *
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception {
        java.util.Base64.Decoder base64Decoder = java.util.Base64.getDecoder();
        return StringUtils.isEmpty(base64Code) ? null : base64Decoder.decode(base64Code);
    }

    /**
     * 生成签名数据
     *
     * @param data 待加密的数据
     * @param key  加密使用的key
     * @throws Exception
     */
    public static byte[] getSignature(byte[] data, String key) throws Exception {
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        return mac.doFinal(data);
    }

    /**
     * 生成签名数据
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String getSignatureString(String data, String key) throws Exception {
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        return base64Encode(mac.doFinal(data.getBytes("UTF-8")));
    }

    /**
     * AES加密
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(encryptKey.getBytes()));

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // cipher.init(Cipher.ENCRYPT_MODE, new
        // SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }

    /**
     * AES加密为base 64 code
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES解密
     *
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey   解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(decryptKey.getBytes()));

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);

        return new String(decryptBytes);
    }

    /**
     * 将base 64 code AES解密
     *
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static String getRandomAesKey() {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            int number = random.nextInt(base.length());
            sb.append(Integer.toHexString(number));
        }
        return sb.toString();
    }

    /**
     * 验证签名
     *
     * @param obj
     * @return
     */
    public static String verifySign(JSONObject obj) {

        StringBuffer sb = new StringBuffer();
        Set<String> keySet = obj.keySet();
        String[] strs = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(strs);
        for (String s : strs) {
            String value = obj.get(s).toString();
            if (value != null && !"sign".equals(s)) {
                sb.append(s + "=" + value);
                sb.append("&");
                continue;
            }
        }
        String str = sb.substring(0, sb.length() - 1);
        String str_md5 = MD5Util.string2MD5(str);
        return str_md5;
    }

    /**
     * 获取待加密字符串
     *
     * @param obj
     * @return
     */
    public static String getJsonStr2Sign(JSONObject obj) {

        StringBuffer sb = new StringBuffer();
        Set<String> keySet = obj.keySet();
        /* Iterator<String> itt = obj.keys(); */
        String[] strs = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(strs);
        for (String s : strs) {
            String value = obj.get(s).toString();
            if (value != null && !"sign".equals(s) && !"sign_type".equals(s)) {
                sb.append(s + "=" + value);
                sb.append("&");
                continue;
            }
        }
        String str = sb.substring(0, sb.length() - 1);
        return str;
    }

    /**
     * 获取待加密字符串=-------三方支付所用
     *
     * @param obj
     * @return
     */
    public static String getJsonStr2SignThirdPay(JSONObject obj) {

        StringBuffer sb = new StringBuffer();
        Set<String> keySet = obj.keySet();
        /* Iterator<String> itt = obj.keys(); */
        String[] strs = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(strs);
        for (String s : strs) {
            String value = obj.get(s).toString();
            if (value != null && !"sign".equals(s) && !"sign_type".equals(s) && !"dpcode".equals(s) && !"SERVERID".equals(s)
                    && !"serverid".equals(s)) {
                sb.append(s + "=" + value);
                sb.append("&");
                continue;
            }
        }
        String str = sb.substring(0, sb.length() - 1);
        return str;
    }

    /**
     * 计算云支付接口签名
     *
     * @param body
     * @param appKey
     * @return
     * @throws Exception
     */
    public static String getCloudPaySign(JSONObject body, String appKey) throws Exception {
        Set<String> keySet = body.keySet();
        String[] keys = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keys);
        if (body.containsKey("jsondata")) {
            JSONObject jsonData = body.getJSONObject("jsondata");
            JSONObject treeMap = new JSONObject(new TreeMap<String, Object>());
            Set<String> jkeySet = jsonData.keySet();
            String[] jkeys = jkeySet.toArray(new String[jkeySet.size()]);
            Arrays.sort(jkeys);
            for (String key : jkeys) {
                treeMap.put(key, jsonData.get(key));
            }
            body.put("jsondata", treeMap);
        }
        StringBuffer str = new StringBuffer();
        for (String key : keys) {
            String value = body.getString(key);
            if (StringUtils.isNotBlank(value) && !"sign".equals(key)) {
                str.append(key + "=" + value);
                str.append("&");
            }
        }
        str.append("key=" + appKey);
        return getSignatureString(str.toString(), appKey).toUpperCase();
    }

    public static String getCloudPaySign(String body, String appKey) throws Exception {
        JSONObject obj = JSON.parseObject(body);
        return getCloudPaySign(obj, appKey);
    }

    public static void main(String[] args) throws Exception {
        Map<String,Object> retMap=new LinkedHashMap<>();
        retMap.put("method","getBuildingGateList");
        Map<String,Object> paramMap=new LinkedHashMap<>();
        ArrayList arrayList=new ArrayList();
        Map<String,Object> gateMap=new LinkedHashMap<>();
        gateMap.put("gate","学校大门南门-1");
        gateMap.put("type",1);
        gateMap.put("buildingId",145);
        arrayList.add(gateMap);
        paramMap.put("gates",arrayList);
        paramMap.put("schoolName","新开普大学");
        paramMap.put("qrcodeUrl","reportSys:passcard");
        retMap.put("param",paramMap);
        retMap.put("retcode",200);
        retMap.put("retmsg","ok");
        String str = JSONObject.toJSONString(retMap, true);
        System.out.println(str);
        System.out.println(SignUtils.getSignatureString(str,"12345"));
    }

}
